package com.irdstudio.devops.agent.plugin.maven;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.bfp.executor.core.plugin.AbstractPlugin;
import com.irdstudio.bfp.executor.core.plugin.common.SParamInfo;
import com.irdstudio.bfp.executor.rest.init.ExecutorResourceLoader;
import com.irdstudio.devops.agent.dao.BpmNodeInfoDao;
import com.irdstudio.devops.agent.plugin.git.PluginGitConf;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.InvokerLogger;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamLogger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MavenPlugin extends AbstractPlugin {

    private String pluginName = null;
    private MavenConf pluginParam = null;
    private PluginGitConf gitConf=null;
    private String taskName = null;
    private int pluginId;
    private SParamInfo localPath =null;
    private SParamInfo mavenHome=null;
    private SParamInfo mavenSettings=null;
    private String bpmId;
    private String appPathLastName;

    @Override
    protected boolean doReadConfigureFromDB(Connection conn, String szConfIdentify) throws SQLException {
        pluginName = context.getSzPluginName();
        taskName = context.getSzTaskName();
        pluginId = context.getnPluginId();
        pluginParam = context.getSzPluginParam(MavenConf.class);
        bpmId = context.getSzBatchId();
        //通过自动流程标识获取git插件node节点
        BpmNodeInfoDao bpmNodeInfoDao = new BpmNodeInfoDao(conn);
        String gitParam = bpmNodeInfoDao.queryByBpmIdAndBpmNodeCode(bpmId,"1095").getBpmNodeParam();
        //字符串转对象
        PluginGitConf gitConf = JSONObject.parseObject(gitParam, PluginGitConf.class);
        //获取工程名
        int firstIndex = gitConf.getGitRemotePath().lastIndexOf("/");
        int lastIndex = gitConf.getGitRemotePath().lastIndexOf(".");
        appPathLastName  = gitConf.getGitRemotePath().substring(firstIndex, lastIndex);

        //获取插件全局参数
        List<SParamInfo> paramInfos = new ArrayList();
        paramInfos.addAll(ExecutorResourceLoader.me().getPluginGlobalParam(Integer.toString(pluginId)));

        for (int i = 0; i < paramInfos.size(); i++) {
            switch (paramInfos.get(i).getParamCode()){
                case "localPath":
                    localPath = paramInfos.get(i);
                    break;
                case "mavenHome":
                    mavenHome = paramInfos.get(i);
                    break;
                case "mavenSettings":
                    mavenSettings = paramInfos.get(i);
                    break;
            }
        }

        if (pluginParam ==null || mavenHome==null || localPath ==null ||mavenSettings == null)
        {
            context.setSzLastErrorMsg("未读取到配置标识为：" + szConfIdentify + "的数据MySQL配置!");
            return false;
        }else {
            return true;
        }
    }

    @Override
    public boolean execute() throws Exception {

        logger.info("调用Maven编译插件，编译应用: "+ taskName);
        String projectPomPath = localPath.getParamValue()+appPathLastName + File.separator + "pom.xml";
        logger.info("pom文件："+projectPomPath);
        InvocationRequest request = new DefaultInvocationRequest();
        if (StringUtils.isNotBlank(mavenSettings.getParamValue())) {
            request.setUserSettingsFile(new File(mavenSettings.getParamValue()));
        }
        request.setPomFile(new File(projectPomPath));
        request.setGoals(Arrays.asList(pluginParam.getMavenSettings()));

        Invoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(mavenHome.getParamValue()));

        invoker.setLogger(new PrintStreamLogger(System.err, InvokerLogger.WARN) {
        });
        invoker.setOutputHandler(new InvocationOutputHandler() {
            @Override
            public void consumeLine(String s) throws IOException {
                System.out.println(s);
                logger.info(s);
            }
        });
        boolean flag = true;
        InvocationResult result = null;
        try {
            result = invoker.execute(request);
            flag = true;
        } catch (MavenInvocationException e) {
            e.printStackTrace();
            logger.error(e);
            context.setSzLastErrorMsg(e.getMessage());
            flag = false;
        }

        if (flag) {
            if (result.getExitCode() == 0) {
                logger.info("maven plugin build success");
                flag = true;
            } else {
                logger.info("maven plugin build error");
                context.setSzLastErrorMsg("Maven编译失败");
                flag = false;
            }
        }
        invoker = null;
        return flag;
    }
}
